<template>
  <div class="pool-management">
    <!-- 主要内容区域 -->
    <div class="main-content-wrapper">
      <el-card>
        <!-- 搜索区域 -->
        <el-form :model="searchForm" class="search-form" label-width="80px">
          <el-row :gutter="20" align="middle">
            <el-col :span="6">
              <el-form-item label="商机ID" inline>
                <el-input
                  v-model="searchForm.businessId"
                  placeholder="请输入商机ID"
                  style="width: 180px"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="客户姓名" inline>
                <el-input
                  v-model="searchForm.name"
                  placeholder="请输入客户姓名"
                  style="width: 180px"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="手机号" inline>
                <el-input
                  v-model="searchForm.phone"
                  placeholder="请输入手机号"
                  style="width: 180px"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="意向学科" inline>
                <el-select
                  v-model="searchForm.subject"
                  placeholder="请选择"
                  style="width: 180px"
                >
                  <el-option label="全部" value="" />
                  <el-option label="ai智能应用开发(java)" value="1" />
                  <el-option label="ai大模型开发(python)" value="2" />
                  <el-option label="ai鸿蒙开发" value="3" />
                  <el-option label="ai大数据" value="4" />
                  <el-option label="ai嵌入式" value="5" />
                  <el-option label="ai测试" value="6" />
                  <el-option label="ai运维" value="7" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" style="text-align: right">
              <el-form-item>
                <el-button
                  type="primary"
                  @click="handleSearch"
                  style="margin-right: 10px"
                  >搜索</el-button
                >
                <el-button @click="handleReset">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <!-- 商机表格容器 -->
        <div class="table-container">
          <el-table
            :data="businessList"
            stripe
            style="width: 100%; min-width: 1320px; font-size: 14px; table-layout: fixed;"
            :header-cell-style="{ 'font-size': '14px', padding: '10px 12px' }"
          >
          <el-table-column label="序号" type="index" width="80" />
          <el-table-column prop="id" label="商机ID" width="100" />
          <el-table-column prop="name" label="客户姓名" width="120" />
          <el-table-column prop="phone" label="手机号" width="150" />
          <el-table-column prop="subject" label="意向学科" width="180">
            <template #default="{ row }">
              <el-tag size="small">
                {{ getSubjectText(row.subject) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="channel" label="渠道来源" width="120">
            <template #default="{ row }">
              {{ getChannelText(row.channel) }}
            </template>
          </el-table-column>
          <el-table-column prop="degree" label="学历" width="100">
            <template #default="{ row }">
              {{ getDegreeText(row.degree) }}
            </template>
          </el-table-column>
          <el-table-column prop="jobStatus" label="在职状态" width="100">
            <template #default="{ row }">
              {{ getJobStatusText(row.jobStatus) }}
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column prop="updateTime" label="更新时间" width="180" />
          <el-table-column label="操作" width="100" align="center">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="handleView(row)"
                >查看</el-button
              >
            </template>
          </el-table-column>
          </el-table>
        </div>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 查看商机详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="商机详情"
      width="800px"
      @close="handleCloseDetail"
    >
      <div class="detail-container">
        <!-- 基本信息 -->
        <el-descriptions
          :column="2"
          :border="true"
          label-align="left"
          class="mb-4"
        >
          <el-descriptions-item label="商机ID">{{
            selectedBusiness?.id || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="客户姓名">{{
            selectedBusiness?.name || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{
            selectedBusiness?.phone || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{
            getGenderText(selectedBusiness?.gender)
          }}</el-descriptions-item>
          <el-descriptions-item label="年龄">{{
            selectedBusiness?.age || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="微信">{{
            selectedBusiness?.wechat || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="QQ">{{
            selectedBusiness?.qq || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="学历">{{
            getDegreeText(selectedBusiness?.degree)
          }}</el-descriptions-item>
          <el-descriptions-item label="在职状态">{{
            getJobStatusText(selectedBusiness?.jobStatus)
          }}</el-descriptions-item>
          <el-descriptions-item label="渠道来源">{{
            getChannelText(selectedBusiness?.channel)
          }}</el-descriptions-item>
          <el-descriptions-item label="意向学科">{{
            getSubjectText(selectedBusiness?.subject)
          }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{
            getStatusText(selectedBusiness?.status)
          }}</el-descriptions-item>
          <el-descriptions-item label="下次跟进时间" :span="2">{{
            selectedBusiness?.nextTime || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{
            selectedBusiness?.remark || "-"
          }}</el-descriptions-item>
        </el-descriptions>

        <!-- 跟进记录 -->
        <div
          v-if="
            selectedBusiness?.trackRecords &&
            selectedBusiness.trackRecords.length > 0
          "
        >
          <h4 class="mb-3">跟进记录</h4>
          <el-table
            :data="selectedBusiness.trackRecords"
            stripe
            style="width: 100%; font-size: 14px"
          >
            <el-table-column prop="createTime" label="跟进时间" width="180" />
            <el-table-column prop="assignName" label="跟进人" width="100" />
            <el-table-column prop="trackStatus" label="跟进状态" width="100">
              <template #default="{ row }">
                {{ getTrackStatusText(row.trackStatus) }}
              </template>
            </el-table-column>
            <el-table-column prop="keyItems" label="关键项" width="150">
              <template #default="{ row }">
                {{ formatKeyItems(row.keyItems) }}
              </template>
            </el-table-column>
            <el-table-column prop="record" label="跟进内容" />
          </el-table>
        </div>

        <!-- 无跟进记录 -->
        <div v-else class="no-records">暂无跟进记录</div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";

export default {
  name: "BusinessPoolManagement",
  setup() {
    // 搜索表单
    const searchForm = reactive({
      businessId: "",
      name: "",
      phone: "",
      subject: "",
    });

    // 商机列表数据
    const businessList = ref([]);

    // 分页数据
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0,
    });

    // 详情对话框
    const detailVisible = ref(false);
    const selectedBusiness = ref(null);

    // 获取意向学科文本
    const getSubjectText = (subject) => {
      const subjectMap = {
        1: "ai智能应用开发(java)",
        2: "ai大模型开发(python)",
        3: "ai鸿蒙开发",
        4: "ai大数据",
        5: "ai嵌入式",
        6: "ai测试",
        7: "ai运维",
      };
      return subjectMap[subject] || "未知";
    };

    // 获取渠道来源文本
    const getChannelText = (channel) => {
      const channelMap = {
        1: "线上活动",
        2: "线下活动",
        3: "自然咨询",
        4: "推荐",
      };
      return channelMap[channel] || "未知";
    };

    // 获取学历文本
    const getDegreeText = (degree) => {
      const degreeMap = {
        1: "初中",
        2: "高中",
        3: "中专",
        4: "大专",
        5: "本科",
        6: "硕士",
        7: "博士",
      };
      return degreeMap[degree] || "未知";
    };

    // 获取在职状态文本
    const getJobStatusText = (jobStatus) => {
      const jobStatusMap = {
        1: "在职中",
        2: "待业",
        3: "学生",
      };
      return jobStatusMap[jobStatus] || "未知";
    };

    // 获取性别文本
    const getGenderText = (gender) => {
      if (!gender) return "-";
      const genderMap = {
        1: "男",
        2: "女",
      };
      return genderMap[gender] || "未知";
    };

    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        1: "待分配",
        2: "跟进中",
        3: "已成单",
        4: "已失效",
      };
      return statusMap[status] || "未知";
    };

    // 获取跟进状态文本
    const getTrackStatusText = (trackStatus) => {
      const trackStatusMap = {
        1: "成功",
        2: "失败",
        3: "未接通",
      };
      return trackStatusMap[trackStatus] || "未知";
    };

    // 格式化关键项
    const formatKeyItems = (keyItems) => {
      try {
        const items = JSON.parse(keyItems);
        return Array.isArray(items) && items.length > 0
          ? items.join(", ")
          : "无";
      } catch {
        return "无";
      }
    };

    // 获取商机列表
    const getBusinessList = async () => {
      try {
        const params = {
          ...searchForm,
          page: pagination.currentPage,
          pageSize: pagination.pageSize,
        };

        // 移除空值参数
        Object.keys(params).forEach((key) => {
          if (
            params[key] === "" ||
            params[key] === null ||
            params[key] === undefined
          ) {
            delete params[key];
          }
        });

        // 调用接口获取数据
        const response = await axios.get("/api/businesses/pool", {
          params: params,
        });

        const result = response.data;

        if (result.code === 1) {
          businessList.value = result.data.rows || [];
          pagination.total = Number(result.data.total) || 0;
        } else {
          ElMessage.error(result.msg || "获取商机列表失败");
        }
      } catch (error) {
        console.error("获取商机列表异常:", error);
        ElMessage.error("获取商机列表失败，请稍后重试");
      }
    };

    // 搜索
    const handleSearch = () => {
      pagination.currentPage = 1;
      getBusinessList();
    };

    // 重置
    const handleReset = () => {
      Object.keys(searchForm).forEach((key) => {
        searchForm[key] = "";
      });
      pagination.currentPage = 1;
      getBusinessList();
    };

    // 分页大小改变
    const handleSizeChange = (size) => {
      pagination.pageSize = size;
      getBusinessList();
    };

    // 当前页改变
    const handleCurrentChange = (current) => {
      pagination.currentPage = current;
      getBusinessList();
    };

    // 查看详情
    const handleView = async (row) => {
      try {
        // 调用根据ID查询接口
        const response = await axios.get(`/api/businesses/${row.id}`);
        const result = response.data;

        if (result.code === 1) {
          selectedBusiness.value = result.data;
          detailVisible.value = true;
        } else {
          ElMessage.error(result.msg || "获取商机详情失败");
        }
      } catch (error) {
        console.error("获取商机详情异常:", error);
        ElMessage.error("获取商机详情失败，请稍后重试");
      }
    };

    // 关闭详情对话框
    const handleCloseDetail = () => {
      detailVisible.value = false;
      selectedBusiness.value = null;
    };

    // 组件挂载时获取数据
    onMounted(() => {
      getBusinessList();
    });

    return {
      searchForm,
      businessList,
      pagination,
      detailVisible,
      selectedBusiness,
      getSubjectText,
      getChannelText,
      getDegreeText,
      getJobStatusText,
      getGenderText,
      getStatusText,
      getTrackStatusText,
      formatKeyItems,
      handleSearch,
      handleReset,
      handleSizeChange,
      handleCurrentChange,
      handleView,
      handleCloseDetail,
    };
  },
};
</script>

<style scoped>
.pool-management {
  padding: 20px;
}

.main-content-wrapper {
  overflow-x: auto;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.detail-container {
  max-height: 600px;
  overflow-y: auto;
}

.mb-3 {
  margin-bottom: 16px;
  color: #303133;
  font-weight: 600;
}

.mb-4 {
  margin-bottom: 20px;
}

.no-records {
  text-align: center;
  padding: 40px;
  color: #909399;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.table-container {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  margin-bottom: 16px;
}

/* 页面级滚动条样式 - 更粗更明显 */
::-webkit-scrollbar {
  width: 14px;
  height: 14px;
  display: block;
}

::-webkit-scrollbar-track {
  background: #e0e0e0;
  border-radius: 7px;
}

::-webkit-scrollbar-thumb {
  background: #999;
  border-radius: 7px;
  border: 3px solid #e0e0e0;
}

::-webkit-scrollbar-thumb:hover {
  background: #777;
}

/* 确保水平滚动条始终可见 */
::-webkit-scrollbar-horizontal {
  display: block;
}

/* Firefox滚动条样式 */
html {
  scrollbar-width: thick;
  scrollbar-color: #999 #e0e0e0;
}

/* 优化表格单元格样式，防止内容溢出 */
.table-container .el-table__cell {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
  </style>
